package com.xuan.pmh.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xuan.pmh.util.HttpUtil;
import com.xuan.pmh.util.ShareUtil;

import android.os.Bundle;

/**
 * @author xuan 2014-10-30
 * 
 */
//与网络相关的Activity基类
public abstract class HttpActivity extends BaseActivity {

	private List<PostPacket> requestList = new ArrayList<PostPacket>();
	protected Map<String, String> paramsList=new HashMap<String, String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	//发送请求关键函数
	public synchronized void sendPostRequest() {
		if (requestList.size() == 0) {
			return;
		}
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				final PostPacket pp = requestList.get(0);
				requestList.remove(0);
				try {
					final String result = HttpUtil
							.doPost(ShareUtil.BASE_URL+pp.url+ShareUtil.TAIL, pp.paramsList);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							afterPost(result, pp.requestCode,pp.paramsList);
						}
					});
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	//添加发送请求
	public void addPostRequest(String url, Map<String, String> paramsList,
			int requestCode) {
		requestList.add(new PostPacket(url, paramsList, requestCode));
	}

	//发送请求bean
	class PostPacket {
		String url;
		Map<String, String> paramsList;
		int requestCode;

		public PostPacket(String url, Map<String, String> paramsList,
				int requestCode) {
			// TODO Auto-generated constructor stub
			this.url = url;
			this.paramsList = paramsList;
			this.requestCode = requestCode;
		}
	}

	//待完成函数,发送请求后回调该函数
	public abstract void afterPost(String result, int requestCode,Map<String, String> request);

}

